<?php


namespace app\admin\controller;

use app\admin\command\Install;
use support\annotation\NoNeedRight;
use support\Request;
use support\util\TreeArray;
use support\Validator;
use support\View;
use app\admin\model\Menu as Model;

class Menu extends BaseController
{
    protected $preViewName = 'menu';

    public function show(Request $request)
    {
        $id = $request->get('id', null);
        if ($id !== null) {
            $row = Model::query()->find($id);
            View::assign('row', $row);
        }
        return $this->view('show', [
            'pid' => $request->get('pid', isset($row) ? $row->pid : 0),
            'targetList' => Model::getTragetList(),
            'typeList' => Model::getTypeList(),
            'statusList' => Model::getStatusList(),
            'treeList' => Model::getTreeSelect()
        ]);
    }

    public function index(Request $request)
    {
        if ($request->expectsJson()) {
            $list = Model::query()->orderByDesc('weigh')->get();
            $this->success("获取成功", $list);
        }
        return $this->view('index');
    }

    /**
     * @NoNeedRight()
     */
    public function select() {
        $this->success("获取成功", Model::getTreeSelect());
    }

    public function createjson()
    {
        $list = Model::query()->orderByDesc('weigh')->orderByDesc('created_at')->get();
        $tree = TreeArray::instance();
        $tree->init($list->toArray());
        file_put_contents(Install::MENU_JSON_PATH, json_encode($tree->getTreeArray(0), JSON_UNESCAPED_UNICODE));
        $this->success();
    }

    protected function store(Request $request)
    {
        $form = $request->post('form');
        Validator::getInstance()->validate($form, [
            'type' => 'required',
            'title' => 'required',
            'status' => 'required',
            'target' => 'required'
        ], [
            'required' => ':attribute必填',
        ], [
            'type' => '类型',
            'title' => '标题',
            'status' => '状态',
            'target' => '打开方式',
        ]);
        if (isset($form['id'])) {
            $row = Model::query()->where('id', $form['id'])->first();
            if (!$row) {
                $this->error('未找到!');
            }
            unset($form['id']);
        }else {
            $row = new Model();
        }
        if (isset($form['pid']) && $form['pid'] != 0) {
            $prow = Model::query()->where('id', $form['pid'])->first();
            if ($prow) {
                $form['pids'] = $prow->pids . ',' . $prow->id;
            }
        }
        $row->fill($form);
        $row->save();
        $this->success("操作成功!");
    }
}
